<template>
	<view class="container">
		<view class="recordInput formItem">
			<textarea
				:disabled="getReadOnly()"
				:placeholder="type === 1 ? '添加日程内容' : '添加行动措施内容'"
				@input="({ detail }) => (scheduleContent = detail.value)"
				:value="scheduleContent"
			></textarea>
			<template v-if="getReadOnly()">
				<view class="w100 df fdc df-g20">
					<diy-audio
						v-for="rec in recordList"
						v-bind:key="rec.filePath"
						:audioTime="rec.time"
						:voiceText="rec.voiceText"
						:file="rec.filePath"
					></diy-audio>
				</view>
			</template>
			<template v-else>
				<reportRecord
					:showText="false"
					:audioUrl="recordList"
					@delete="deleteReportItem"
					class="record"
					@upload="getReportRecord"
				></reportRecord>
			</template>
		</view>
		<view class="formItem" v-if="type === 1">
			<view class="icon"
				><image
					src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/pm287hpbhdeae078od9hsmweh.png?timestamp=1687873278296"
				></image
			></view>
			<view class="formInput time-picker">
				<input
					class="uni-input"
					:value="dayTimeMonth + ' ' + scheduleStartTime"
					disabled
					placeholder="开始时间"
					@click="chooseTime('start')"
				/>
				<view>至</view>
				<input
					class="uni-input"
					:value="dayTimeMonth + ' ' + scheduleEndTime"
					disabled
					placeholder="结束时间"
					@click="chooseTime('end')"
				/>
			</view>
		</view>
		<view class="formItemWrapper">
			<view class="formItem">
				<view class="icon">
					<image
						src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/k487sz1ur7ovx1blsvvzw9evr.png?timestamp=1687873308094"
					></image>
				</view>
				<view class="formInput" @click="chooseUserItem">
					<view class="label">添加参与人</view>
					<view class="values">{{ checkedUserNames }}</view>
					<uni-icons
						class="right"
						type="right"
						size="20"
						color="#999999"
					></uni-icons>
				</view>
			</view>
			<view v-if="isEdit" class="formItemMarker">
				{{
					scheduleDetailInfo.agreeList
						? scheduleDetailInfo.agreeList.length
						: 0
				}}人
				<text>接受</text>
				,
				{{
					scheduleDetailInfo.agreeList
						? scheduleDetailInfo.refuseList.length
						: 0
				}}人
				<text class="red">拒绝</text>
				<view class="toRefuseDetail" @click="openPartUserListDialog"
					>查看详情</view
				>
			</view>
		</view>
		<view class="formItem">
			<view class="icon"
				><image
					src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/n4gax7rif5apf31y5ibajrkwq.png?timestamp=1687873220058"
				></image
			></view>
			<view class="formInput">
				<view class="label">优先级</view>
				<view class="values" :class="getReadOnly() ? 'disabled' : ''">
					<view
						class="value"
						:class="opt.value === level ? 'active-' + index : ''"
						v-for="(opt, index) in levelOptions"
						v-bind:key="opt.value"
						:style="colors[index] ? 'color:' + colors[index] : ''"
						@click="level = opt.value"
					>
						{{ opt.label }}
					</view>
				</view>
			</view>
		</view>
		<view class="formItem" v-if="type === 2">
			<view class="icon"
				><image
					src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/n4gax7rif5apf31y5ibajrkwq.png?timestamp=1687873220058"
				></image
			></view>
			<view class="formInput" @click="openUrgency">
				<view class="label">完成紧急度</view>
				<view class="values">{{ showUrgency(urgencyValue) }}</view>
				<uni-icons
					class="right"
					type="right"
					size="20"
					color="#999999"
				></uni-icons>
			</view>
		</view>

		<view class="formItem">
			<view class="icon"
				><image
					src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/vawm3mece426er3j6oprod0sh.png?timestamp=1687873336758"
				></image
			></view>
			<view class="formInput">
				<view class="label">标签</view>
				<view class="values" :class="getReadOnly() ? 'disabled' : ''">
					<view
						class="value"
						:class="_label.value === label ? 'active' : ''"
						v-for="_label in labelOptions"
						v-bind:key="_label.value"
						@click="label = _label.value"
					>
						{{ _label.label }}
					</view>
				</view>
			</view>
		</view>
		<view v-if="label === 3">
			<template v-if="scheduleId">
				<view v-if="orderMeetingValue !== 0" class="formItem">
					<view class="icon"
						><image
							src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/vawm3mece426er3j6oprod0sh.png?timestamp=1687873336758"
						></image
					></view>
					<view class="formInput">
						<view class="label">同时预定会议</view>
						<text>{{ orderMeetingValueSpace }}</text>
					</view>
				</view>
			</template>
			<view v-else class="formItem">
				<view class="icon"
					><image
						src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/vawm3mece426er3j6oprod0sh.png?timestamp=1687873336758"
					></image
				></view>
				<view class="formInput">
					<view class="label">同时预定会议</view>
					<view
						class="values"
						:class="getReadOnly() ? 'disabled' : ''"
					>
						<view
							class="value"
							:class="
								_label.value === orderMeetingValue
									? 'active'
									: ''
							"
							v-for="_label in orderMeetingOptions"
							v-bind:key="_label.value"
							@click="orderMeetingValue = _label.value"
						>
							{{ _label.label }}
						</view>
					</view>
				</view>
			</view>
		</view>
		<template v-if="!isPartUser">
			<view class="formItemWrapper">
				<view class="formItem">
					<view class="icon">
						<image
							src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/wqjo5qcpw5scmwn0kpwcjz0lq.png?timestamp=1687873473797"
						></image>
					</view>
					<view class="formInput">
						<view class="label">通知他人方式</view>
						<view
							class="values"
							:class="getReadOnly() ? 'disabled' : ''"
						>
							<view
								class="value"
								:class="
									item.value === reminderType ? 'active' : ''
								"
								v-for="item in noticeTypes"
								v-bind:key="item.value"
								@click="reminderType = item.value"
							>
								{{ item.label }}
							</view>
						</view>
					</view>
				</view>
				<view
					v-if="needCheckWeworkList.length && reminderType === 2"
					class="formItemMarker"
					style="display: block"
				>
					您选择的 {{ checkedUserIds.length - 1 }} 个参与者中，
					<text class="red">{{
						needCheckWeworkList.join('、')
					}}</text>
					未添加办公助手微信，无法通过微信通知，请先通知参与者添加办公助手微信
				</view>
			</view>
			<view class="formItem" v-if="type === 1">
				<view class="icon">
					<image
						src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/uy6k8jfpqvijwcmkh2d1rjjdl.png?timestamp=1687873356689"
					></image>
				</view>
				<view class="formInput" @click="openNoticeSetting">
					<view>{{ noticeSettingTip }}</view>
					<uni-icons
						class="right"
						type="right"
						size="20"
						color="#999999"
					></uni-icons>
				</view>
			</view>
		</template>
		<view
			class="cancelTip"
			v-if="[3, 4].includes(scheduleDetailInfo.scheduleStatus)"
		>
			<template v-if="scheduleDetailInfo.scheduleStatus === 4">
				<text>创建者已取消{{ type === 1 ? '日程' : '行动措施' }}</text>
				<image
					class="waterMark"
					src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/dhm35t6mlsklidg58h0y18b53.png?timestamp=1686988968140"
				></image>
			</template>
			<template v-else>
				<image
					class="waterMark"
					style="height: 150rpx"
					src="https://yilife-oss-online-public.oss-cn-hangzhou.aliyuncs.com/10000001/1015/ADMIN/mbr3rega7on5x0malk1ud0w8i.png?timestamp=1676896860481"
				></image>
			</template>
		</view>
		<view v-else class="footer">
			<template v-if="isPartUser">
				<view class="partUserAction">
					<template v-if="scheduleDetailInfo.userAgree === 2">
						<text
							>您已拒绝该{{
								type === 1 ? '日程' : '行动措施'
							}}</text
						>
						<image
							class="waterMark"
							src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/131044/ORG/7ivkgn2wwnyel9kkoqscocvl2.png?timestamp=1687165159751"
						></image>
					</template>
					<template v-else>
						<text
							>您已默认接受该{{
								type === 1 ? '日程' : '行动措施'
							}}</text
						>
						<button
							class="primary-button btn default-button linear red"
							@click="showRejectForm = true"
						>
							拒绝{{ type === 1 ? '日程' : '行动措施' }}
						</button>
						<button
							class="primary-button linear btn w100"
							@click="joinMeeting"
						>
							加入会议
						</button>
					</template>
				</view>
				<rejectMeeting
					v-show="showRejectForm"
					:scheduleId="scheduleDetailInfo.id"
					@onRejectionConfirm="onRejectionConfirm"
					@onRejectionCancel="onRejectionCancel"
				></rejectMeeting>
			</template>
			<template v-else>
				<template v-if="isEdit">
					<view class="btn-row">
						<button
							class="primary-button linear btn w100"
							@click="joinMeeting"
						>
							加入会议
						</button>
						<button
							class="primary-button linear btn w100"
							@click="createAction"
						>
							修改{{ type === 1 ? '日程' : '行动措施' }}
						</button>
					</view>
					<button
						class="second-button w100 mt10"
						@click="cancelAction"
					>
						取消{{ type === 1 ? '日程' : '行动措施' }}
					</button>
				</template>
				<template v-else>
					<button
						class="primary-button linear btn w100"
						@click="createAction"
					>
						完成{{ type === 1 ? '日程' : '行动措施' }}创建
					</button>
				</template>
			</template>
		</view>
		<view
			class="tr f28 mt20"
			v-if="scheduleDetailInfo.workJournalScheduleVO"
			@click="
				goReportDetail(
					scheduleDetailInfo.workJournalScheduleVO.journalId
				)
			"
		>
			本{{
				scheduleDetailInfo.scheduleCategory === 2 ? '行动措施' : '日程'
			}}来自
			<text class="primary-color">{{
				scheduleDetailInfo.workJournalScheduleVO.title
			}}</text>
		</view>
		<template v-if="!getReadOnly()">
			<!--日期 & 时间段选择-->
			<diy-dateselect
				:show="dateSelectShow"
				:value="[dayTime, scheduleStartTime]"
				@close="dateSelectShow = false"
				@submit="submitChooseDate"
			></diy-dateselect>
			<!--时间段选择-->
			<diy-dateselect
				:halfTrue="true"
				:show="timeSelectShow"
				@close="timeSelectShow = false"
				@submit="submitChooseDate"
				:minDate="[dayTime, scheduleStartTime]"
				:value="[dayTime, scheduleEndTime]"
			></diy-dateselect>
			<!-- 选择成员 -->
			<user-list
				ref="userRefs"
				:userList="userData"
				:checkedFixId="myUserId"
				:checkedIds="checkedUserIds"
				@complete="updateUserList"
			></user-list>
			<!-- 日程提醒 设置 -->
			<noticeSetting
				ref="noticeSettingRefs"
				@complete="settingNotice"
			></noticeSetting>
			<!-- 紧急度设置 -->
			<urgencySetting
				ref="urgencySettingRefs"
				@complete="settingUrgency"
			></urgencySetting>
		</template>
		<partUserListDialog ref="partUserListDialogRefs"></partUserListDialog>
	</view>
</template>
<script>
const dayjs = require('@/common/dayjs.min.js')
const colors = ['', '#EC6560', '#d6837c']
import { handleFormatDayjs } from '@/common/date'
import { unique } from '@/common/utils'
import {
	levelOptions,
	typeOptions,
	labelOptions,
	noticeTypes,
	noticeTimeOptions,
	urgencyOptions,
	getUrgencyOptionItem,
	scheduleStatusOptions,
	orderMeetingOptions,
} from './config'
import userList from '../components/userList.vue'
import noticeSetting from '../components/noticeSetting.vue'
import urgencySetting from '../components/urgencySetting.vue'
import reportRecord from '@/subPackagesLog/components/reportRecord/reportRecord.vue'

import partUserListDialog from '../components/partUserListDialog.vue'
import rejectMeeting from '../components/scheduleRejMeeting.vue'

import {
	addSchedule,
	updateSchedule,
	cancelSchedule,
	checkRelation,
	scheduleDetail,
	writeToCalendar,
	getContentByDate,
} from '@/apis/calendar'
import diyAudio from '@/subPackagesLog/components/diy-audio/diy-audio.vue'
import { insertSpace } from '@/common/utils.js'

const successToast = (title) => {
	uni.showToast({
		title,
	})
	setTimeout(() => {
		const pages = getCurrentPages()
		if (pages.length > 1) {
			// let pages = getCurrentPages();  //获取所有页面栈实例列表
			// let nowPage = pages[ pages.length - 1];  //当前页页面实例
			// let prevPage = pages[ pages.length - 2 ];  //上一页页面实例
			// prevPage.$vm?.otherFun && prevPage.$vm.otherFun(true);

			uni.navigateBack({
				delta: 1,
				fail() {
					uni.redirectTo({
						url: '/subPackagesLog/pages/workLog/index',
					})
				},
			})
		} else {
			uni.redirectTo({
				url: '/subPackagesLog/pages/workLog/index',
			})
		}
	}, 1000)
}

export default {
	data() {
		return {
			scheduleDetailInfo: {
				agreeList: [],
				refuseList: [],
				scheduleStatus: 1,
			},
			emptyFn: () => {},
			isEdit: false,
			isPartUser: false,
			scheduleId: '',
			scheduleContent: '',
			recordList: [],
			rejectRecordList: [],
			type: typeOptions[0].value,
			date: Date.now(),
			levelOptions,
			labelOptions,
			level: levelOptions[0].value,
			colors,
			label: labelOptions[2].value,
			noticeTypes,
			reminderType: '',
			scheduleStartTime: '',
			scheduleEndTime: '',
			dateSelectShow: false,
			timeSelectShow: false,
			currentDateType: 'start',
			dayTime: '',
			dayTimeMonth: '',
			userData: [],
			checkedUserNames: '',
			needCheckWeworkList: [],
			checkedUserIds: [uni.getStorageSync('userId')],
			myUserId: uni.getStorageSync('userId'),
			noticeSettingList: [
				{
					time: noticeTimeOptions[2].value,
					type: noticeTypes[1].value,
				},
			],
			noticeSettingTip: '开始前15分钟，微信通知提醒我',
			urgencyOptions,
			urgencyValue: 0,
			showRejectForm: false,
			rejectContent: '',
			journalId: '',
			journalDetailId: '',
			text: '',
			dailyId: '',
			orderMeetingOptions,
			orderMeetingValue: 1, //写了个假的
		}
	},
	computed: {
		orderMeetingValueSpace() {
			if (this.orderMeetingValue !== 0)
				return insertSpace(this.orderMeetingValue)
			return ''
		},
	},
	components: {
		userList,
		noticeSetting,
		urgencySetting,
		reportRecord,
		partUserListDialog,
		diyAudio,
		rejectMeeting,
	},
	onReady() {
		const prefixTitle = this.scheduleId ? '查看' : ' 新增'
		const title = this.scheduleId
			? '详情'
			: prefixTitle + (this.type === 1 ? '日程' : '行动措施')
		uni.setNavigationBarTitle({
			title,
		})
	},
	onLoad(options) {
		const { type, date, scheduleId, text, dailyId, journalDetailId } =
			options
		console.log(options)
		this.type = type || typeOptions[0].value
		this.date = date || Date.now()
		this.scheduleId = scheduleId
		this.text = text
		this.dailyId = dailyId
		this.journalDetailId = journalDetailId
	},
	onShow() {
		if (uni.getStorageSync('token')) {
			this.checkedUserIds = [uni.getStorageSync('userId')]
			if (this.scheduleId) {
				const orgId = uni.getStorageSync('orgId')
				const scheduleId = this.scheduleId
				scheduleDetail({ scheduleId, orgId }).then((res) => {
					const item = res.data
					//@Todo: 例行日程，先跳转到老页面
					if (item.scheduleType === 3) {
						uni.redirectTo({
							url: `/subPackagesLog/pages/workLog/workLogDetail?id=${item.id}&templateId=${item.templateId}&scheduleStandardDate=${item.scheduleStandardDate}`,
						})
					} else {
						this.scheduleDetailInfo = {
							...this.scheduleDetailInfo,
							...item,
						}
						this.initDetailData(item)
					}
				})
			} else {
				if (this.text) {
					this.journalId = this.dailyId || ''
					this.journalDetailId = this.journalDetailId || ''
					getContentByDate({ content: this.text }).then((res) => {
						const fromData = res.success
							? dayjs(
									res.data.split(' ').length === 1
										? res.data +
												handleFormatDayjs(
													dayjs(),
													'HH:mm'
												)
										: res.data
							  ).valueOf()
							: this.date
						this.initCreateData(this.type, fromData)
					})
				} else {
					this.initCreateData(this.type, this.date)
					this.journalId = this.dailyId || ''
					this.journalDetailId = this.journalDetailId || ''
				}
			}
			this.getUserData()
		} else {
			uni.navigateTo({
				url: '/subPackagesIndex/pages/index/authorization/index',
			})
		}
	},
	methods: {
		handleFormatDayjs,
		goReportDetail(id) {
			if (
				this.scheduleDetailInfo.workJournalScheduleVO
					.journalDetailViewFlag === false
			) {
				uni.showToast({
					title: '您暂无查看权限',
					icon: 'none',
				})
				return
			} else {
				const type = 'approval'
				uni.navigateTo({
					url: `/subPackagesLog/pages/workLog/reportDetail?id=${id}&type=${type}`,
				})
			}
		},
		// 编辑查看入口
		initDetailData(data) {
			const {
				scheduleContent,
				scheduleCategory,
				scheduleStandardDate,
				scheduleStartTime,
				scheduleEndTime,
				voiceDTOS = [],
				partUserIds,
				schedulePriority,
				completeUrgency,
				workJournalReminderVOS: workJournalReminderDTOS,
				reminderType = 1,
				userId,
				scheduleLabelId,
				preMeetingCode,
			} = data

			// 是否创建者
			this.isEdit = this.myUserId === userId
			// 是否是参与者
			this.isPartUser = this.myUserId !== userId

			const scheduleStartTimeDate = dayjs(
				scheduleStandardDate + 'T' + scheduleStartTime
			)

			this.scheduleContent = scheduleContent
			this.checkedUserIds = unique([
				...this.checkedUserIds,
				...partUserIds,
			])
			this.level = schedulePriority
			this.label = scheduleLabelId
			// 默认立即完成
			this.urgencyValue = completeUrgency || '0'
			this.reminderType = reminderType
			this.orderMeetingValue = preMeetingCode

			// 提醒设置初始化
			this.settingNotice({
				settings: (workJournalReminderDTOS || []).map(
					({ reminderType, reminderTime }) => ({
						type: reminderType,
						time:
							(scheduleStartTimeDate.valueOf() - reminderTime) /
							60000,
					})
				),
			})

			// 检查下微信绑定情况
			this.checkRelationForWework(this.checkedUserIds)

			// 重新设置标题
			uni.setNavigationBarTitle({
				title:
					'查看' +
					(this.scheduleCategory === 1 ? '日程' : '行动措施'),
			})

			this.recordList = voiceDTOS.map(
				({ voiceDuration, voiceText, voiceUrl }) => ({
					time: voiceDuration,
					voiceText,
					filePath: voiceUrl,
					count: voiceDuration,
					//@Todo：需要优化-控制语音不自动播放
					playStatus: 0,
				})
			)

			this.initCreateData(
				scheduleCategory || 1,
				scheduleStartTimeDate,
				scheduleEndTime
			)
		},
		initCreateData(type, date, scheduleEndTime) {
			this.type = Number(type)
			this.date = dayjs(Number(date))
			this.timeAreaSetting(scheduleEndTime)
		},
		timeAreaSetting(scheduleEndTime) {
			const isZeroMinTime = this.date.minute() < 1
			const nextHourTime = this.date.add(isZeroMinTime ? 1 : 2, 'hour')
			this.scheduleStartTime =
				handleFormatDayjs(
					isZeroMinTime ? this.date : this.date.add(1, 'hour'),
					'HH'
				) + ':00'
			// 不跨天，则设置最大结束日程时间段
			if (nextHourTime.isSame(this.date, 'day')) {
				this.scheduleEndTime =
					scheduleEndTime ||
					handleFormatDayjs(nextHourTime, 'HH') + ':00'
			} else {
				this.scheduleEndTime = '23:59'
			}
			this.dayTime = handleFormatDayjs(this.date)
			this.dayTimeMonth = handleFormatDayjs(this.date, 'M月D日')
		},
		chooseTime(t) {
			this.currentDateType = t
			if (t === 'start') {
				this.dateSelectShow = true
			} else {
				this.timeSelectShow = true
			}
		},
		submitChooseDate(val) {
			if (this.currentDateType == 'start') {
				this.date = dayjs(val.join('T'))
				this.timeAreaSetting()
			} else {
				this.scheduleEndTime = val
			}
		},
		chooseUserItem() {
			this.$refs.userRefs?.init()
		},
		updateUserList({ checkedIds }) {
			this.checkedUserIds = checkedIds
			this.checkRelationForWework(checkedIds)
		},
		checkRelationForWework(checkedIds = this.checkedUserIds) {
			return checkedIds.length
				? checkRelation({
						partUserIds: checkedIds.filter(
							(id) => id !== this.myUserId
						),
				  }).then((res) => {
						this.needCheckWeworkList =
							res?.data
								?.map((d) => this.getName(d.userId))
								?.filter((v) => v) || []
						return this.needCheckWeworkList
				  })
				: []
		},
		getName(id) {
			return this.userData.filter((u) => u.id === id)[0]?.name
		},
		// 获取用户列表
		getUserData() {
			this.$request
				.request(
					'carer-platform/work/log/schedule/getWorkJournalTemplateUserList',
					{
						method: 'get',
						data: {
							orgId: uni.getStorageSync('orgId'),
							pageIndex: 1,
							pageSize: 5000,
						},
					}
				)
				.then((res) => {
					this.userData = res.data.data || []
				})
		},
		openNoticeSetting() {
			this.$refs.noticeSettingRefs?.open(this.noticeSettingList)
		},
		settingNotice(value = {}) {
			const values = value.settings || []
			this.noticeSettingList = values
			if (values.length) {
				const { type, time } = values[0]
				this.noticeSettingTip =
					noticeTimeOptions.filter((n) => n.value === time)[0]
						?.label +
					'，' +
					noticeTypes.filter((t) => t.value === type)[0].label +
					'提醒我'
			} else {
				this.noticeSettingTip = '不通知'
			}
		},
		openUrgency() {
			this.$refs.urgencySettingRefs?.open(this.urgencyValue)
		},
		settingUrgency(values) {
			this.urgencyValue = values.value
		},
		openPartUserListDialog() {
			this.$refs.partUserListDialogRefs?.open(
				this.scheduleDetailInfo,
				this.userData
			)
		},
		cancelAction() {
			const scheduleId = this.scheduleId
			uni.showModal({
				title: '确认是否取消日程？',
				success: function (res) {
					if (res.confirm) {
						cancelSchedule({ scheduleId }).then((res) => {
							if (res.success) {
								successToast(res.message)
							}
						})
					}
				},
			})
		},
		async createAction() {
			const orgId = uni.getStorageSync('orgId')
			const scheduleCategory = this.type
			const params = {
				orgId,
				scheduleId: this.scheduleId,
				scheduleType: 1, // 日程类型：1、事件、2、协同、3、例行
				dateType: 2,
				scheduleContent: this.scheduleContent,
				scheduleCategory,
				journalId: this.journalId,
				journalDetailId: this.journalDetailId,
			}

			const scheduleStandardDate = this.dayTime
			const scheduleStartTime = this.scheduleStartTime
			const scheduleEndTime = this.scheduleEndTime
			const schedulePriority = this.level
			const scheduleLabelId = this.label
			const reminderType = this.reminderType
			// 通知设置
			const noticeType = 0
			// 完成紧急度
			const completeUrgency = this.urgencyValue
			const completeUrgencyLabel = this.showUrgency(completeUrgency)
			// 参与人
			const partUserIds = this.checkedUserIds

			// 消息提醒
			const workJournalReminderDTOS = this.noticeSettingList.map(
				({ time, type }) => {
					const reminderDesc = noticeTimeOptions.filter(
						(n) => n.value === time
					)?.[0]?.label
					return {
						reminderDesc,
						reminderType: type,
						reminderTime: dayjs(
							this.dayTime + 'T' + scheduleStartTime
						)
							.subtract(time, 'minute')
							.valueOf(),
						// 给下面的日历创建用
						alarmOffset: time,
					}
				}
			)

			// 语音处理
			const voiceDTOS = this.recordList.map(
				({ time, voiceText, filePath }) => ({
					voiceUrl: filePath,
					voiceDuration: time,
					voiceText,
				})
			)

			// 行动措施，参与人必填
			if (partUserIds.length === 1 && this.type === 2) {
				return uni.showToast({
					title: '请选择参与人',
					icon: 'none',
				})
			}

			if (!reminderType) {
				return uni.showToast({
					title: '请选择通知他人方式',
					icon: 'none',
				})
			}

			if (this.label === 3) {
				// 只有会议被选中时，才传 是否预定会议 preMeetingCode
				params.preMeetingCode = this.orderMeetingValue
			}

			const scheduleActionParam = {
				...params,
				scheduleStandardDate,
				scheduleStartTime,
				scheduleEndTime,
				schedulePriority,
				scheduleLabelId,
				noticeType,
				partUserIds,
				reminderType,
				completeUrgency,
				completeUrgencyLabel,
				voiceDTOS,
			}
			// 日程创建的时候，才会填写
			if (this.type === 1) {
				scheduleActionParam.workJournalReminderDTOS =
					workJournalReminderDTOS
			}
			if (params.scheduleId) {
				updateSchedule(scheduleActionParam).then((res) => {
					if (res.success) {
						successToast(res.message)
					}
				})
			} else {
				addSchedule(scheduleActionParam).then((d) => {
					const scheduleId = d.data
					if (scheduleId) {
						return writeToCalendar({ scheduleId }).then((res) => {
							if (res.success) {
								//日程创建，调用系统日历
								if (scheduleCategory === 1) {
									const calParams = {
										title: params.scheduleContent,
										description: params.scheduleContent,
										startTime: dayjs(
											scheduleStandardDate +
												'T' +
												scheduleStartTime
										).unix(),
										endTime: dayjs(
											scheduleStandardDate +
												'T' +
												scheduleEndTime
										).unix(),
										alarmOffset:
											workJournalReminderDTOS.length
												? workJournalReminderDTOS[0]
														.alarmOffset * 60
												: 0,
										complete: () => {
											successToast(res.message)
										},
									}
									wx?.addPhoneCalendar(calParams)
								} else {
									successToast(res.message)
								}
							}
						})
					} else {
						Promise.reject(d.message)
					}
				})
			}
		},
		getReportRecord(data) {
			const val = data.voiceText
			if (this.isPartUser) {
				this.rejectContent += val
				this.rejectRecordList.push(data)
			} else {
				this.scheduleContent += val
				this.recordList.push(data)
			}
		},
		deleteReportItem(index) {
			if (this.isPartUser) {
				this.rejectRecordList = this.rejectRecordList.filter(
					(_, idx) => idx !== index
				)
			} else {
				this.recordList = this.recordList.filter(
					(_, idx) => idx !== index
				)
			}
		},
		// 拒绝===>
		setCheckedUserNames(ids) {
			const createUserId = this.scheduleDetailInfo.userId || this.myUserId
			// 创建者和 参与者都展示出来
			const joinUsers = this.userData.filter((item) =>
				ids.includes(item.id)
			)
			const names = []
			joinUsers.forEach((user) => {
				if (user.id === createUserId) {
					names.unshift(user.name)
				} else {
					names.push(user.name)
				}
			})
			this.checkedUserNames =
				names.length > 3
					? names.slice(0, 3).join('、') + `等${names.length}人`
					: names.join('、')
		},
		showUrgency(urgencyValue) {
			const item = getUrgencyOptionItem(urgencyValue)
			if (item) {
				return item.label
			}
			return urgencyValue
		},

		getReadOnly() {
			// 参与者 or 已完成/已取消，设置为只读
			return (
				this.isPartUser ||
				[
					scheduleStatusOptions[0].value,
					scheduleStatusOptions[1].value,
				].includes(this.scheduleDetailInfo.scheduleStatus) === false
			)
		},
		joinMeeting() {
			// TODO：加入会议
			wx.navigateToMiniProgram({
				appId: 'wx33fd6cdc62520063',

				path: `pages/sub-preMeeting/join-meeting/join-meeting?m=${this.orderMeetingValue}`,
			})
		},
		onRejectionCancel() {
			this.showRejectForm = false
		},
		onRejectionConfirm(message) {
			successToast(message)
		},
	},
	watch: {
		checkedUserIds(ids) {
			this.setCheckedUserNames(ids)
		},
		userData() {
			this.setCheckedUserNames(this.checkedUserIds)
		},
		reminderType(val) {
			if (val === 2) {
				this.checkRelationForWework()
			}
		},
	},
}
</script>
<style lang="scss" scoped>
.container {
	position: relative;
}
.recordInput {
	display: flex;
	flex-direction: column;
	padding: 20rpx !important;
	textarea {
		width: 100%;
	}
	.record {
		width: 100%;
	}
}

.formItemWrapper,
.formItem {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 30rpx;
	padding: 10rpx 20rpx;
	background: #fff;
	border: 1px solid #eee;
	margin-bottom: 30rpx;
	border-radius: 10rpx;
	.label {
		color: #999;
	}
	.values {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding-left: 10rpx;
		&.disabled {
			position: relative;
			&:after {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				z-index: 2;
			}
		}
		.value {
			line-height: 40rpx;
			border: 2rpx solid #e9e9e9;
			padding: 0 20rpx;
			font-size: 28rpx;
			border-left-width: 0;
			&:first-child {
				border-radius: 6rpx 0 0 6rpx;
				border-left-width: 2rpx;
			}
			&:last-child {
				border-radius: 0 6rpx 6rpx 0;
			}
		}

		.active,
		.active-0 {
			background: $primary-color;
			border-color: $primary-color;
			color: #fff !important;
		}
		.active-1 {
			background: #ec6560;
			border-color: #ec6560;
			color: #fff !important;
		}
		.active-2 {
			background: #d6837c;
			border-color: #d6837c;
			color: #fff !important;
		}
	}
	.right {
		display: flex;
		align-items: center;
	}
}

.formItemWrapper {
	flex-direction: column;
	gap: 10rpx;
	background: transparent !important;
	border-color: transparent !important;
	.formItem {
		width: 100%;
		margin-bottom: 0;
		border-radius: 10rpx;
	}
	.formItemMarker {
		display: flex;
		justify-content: flex-end;
		font-size: 28rpx;
		width: 100%;
		line-height: 1.5;
		.toRefuseDetail {
			color: $primary-color;
			margin-left: 20rpx;
		}
		text {
			color: $primary-color;
			&.red {
				color: $danger-color;
			}
		}
	}
}

.formInput {
	flex: 1;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.time-picker {
	padding: 10rpx 0;
	input {
		// margin-top: 5rpx;
		text-align: center;
	}
}
.icon {
	display: flex;
	align-items: center;
	width: 50rpx;
	image {
		width: 30rpx;
		height: 30rpx;
		object-fit: cover;
	}
}
.footer {
	padding: 30rpx 0;
	button {
		margin-bottom: 20rpx;
	}
	.partUserAction {
		text-align: center;
		text {
			font-size: 32rpx;
			color: $primary-color;
		}
		.red {
			color: $danger-color;
			border-color: $danger-color;
			background: #fff;
		}
	}
}
.cancelTip {
	padding: 40rpx 0;
	text-align: center;
	color: #666666;
}

image.waterMark {
	position: absolute;
	top: 20rpx;
	right: 20rpx;
	width: 160rpx;
	height: 120rpx;
	object-fit: cover;
}
.btn-row {
	display: flex;
	button {
		margin: 0 5px;
		&:first-child {
			margin-left: 0;
		}
		&:last-child {
			margin-right: 0;
		}
	}
}
</style>
